package com.easyUploader.util;

import com.common.exception.CustomException;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;

/**
 * @author 大忽悠
 * @create 2022/11/16 10:52
 */
public class CodeUtil {
    public static final Long CODE_EXPIRE_TIME=30L;
    public static final String CODE_KEY_PREFIX="code:";

    /**
     * @return 生成验证码
     */
    public static String generatorCode(){
        return String.valueOf(System.currentTimeMillis());
    }

    public static String getCodeKey(String eamil){
        return CODE_KEY_PREFIX+eamil;
    }

    /**
     * 如果上次发的验证码还存在,那么不允许继续发送
     */
    public static void codeExistCheck(String eamil) {
        String key = RedisUtil.getKey(CodeUtil.getCodeKey(eamil));
        if (key != null) {
            throw new CustomException("验证码已发送,请过期后再发送", "验证码已发送,请过期后再发送");
        }
    }

    public static void sendCodeAsync(String eamil) {
        //异步执行发送验证码的任务
        CompletableFuture.runAsync(() -> {
            //1.生成验证码
            String code = CodeUtil.generatorCode();
            //2.发送验证码到指定邮箱
            EamilUtil.sendCode(eamil, code);
            //3.保存验证码到redis
            RedisUtil.setKeyEx(CodeUtil.getCodeKey(eamil), code, CODE_EXPIRE_TIME);
        }, Executors.newCachedThreadPool());
    }
}
